package com.hxzy.common.security;


import cn.hutool.core.util.StrUtil;
import com.hxzy.system.vo.AdminLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 * 注意：此拦截器会同时验证当前用户有效期自动刷新有效期
 *
 * @author
 */
@Component
public class JwtTokenInterceptor implements AsyncHandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    /**
     * 前置增强，在执行Controller之前做的验证
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        //是不是SpringMVC的Controller方法
        if (!(handler instanceof HandlerMethod))
        {
            return true;
        }
        //取得令牌
        String token = AdminInfoUtil.getToken(request);
        if (StrUtil.isNotEmpty(token)) {
            //查询redis中是否存在uuid的值
            AdminLoginVO loginUser = this.tokenService.validatorToken(token);
            if (loginUser!=null) {
                SecurityContextHolder.AdminThreadLocal.set(loginUser);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception
    {
        SecurityContextHolder.AdminThreadLocal.remove();
    }
}
